<template>
  <div class="login-bg">
    <div class="login-panel">
    
      <a-tabs v-model:activeKey="activeTab" class="login-tabs">
        <a-tab-pane key="1" tab="账户密码登录">
          <a-form
            ref="formRef"
            :model="formState"
            :rules="rules"
            @finish="handleSubmit"
            layout="vertical"
          >
            <a-form-item name="username">
              <a-input v-model:value="formState.username" placeholder="用户名">
                <template #prefix>
                  <span class="anticon anticon-user" />
                </template>
              </a-input>
            </a-form-item>
            <a-form-item name="password">
              <a-input-password v-model:value="formState.password" placeholder="密码">
                <template #prefix>
                  <span class="anticon anticon-lock" />
                </template>
              </a-input-password>
            </a-form-item>
            <div class="login-options">
              <a-checkbox v-model:checked="autoLogin">自动登录</a-checkbox>
              <a class="login-forgot" href="#">忘记密码？</a>
            </div>
            <a-form-item>
              <a-button 
                type="primary" 
                html-type="submit"
                :loading="loading"
                class="login-btn"
                block
              >
                登录
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
        <a-tab-pane key="2" tab="注册账号">
          <a-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            @finish="handleRegister"
            layout="vertical"
          >
            <a-form-item name="username">
              <a-input v-model:value="registerForm.username" placeholder="用户名">
                <template #prefix>
                  <span class="anticon anticon-user" />
                </template>
              </a-input>
            </a-form-item>
            <a-form-item name="email">
              <a-input v-model:value="registerForm.email" placeholder="邮箱">
                <template #prefix>
                  <span class="anticon anticon-mail" />
                </template>
              </a-input>
            </a-form-item>
            <a-form-item name="password">
              <a-input-password v-model:value="registerForm.password" placeholder="密码">
                <template #prefix>
                  <span class="anticon anticon-lock" />
                </template>
              </a-input-password>
            </a-form-item>
            <a-form-item name="confirmPassword">
              <a-input-password v-model:value="registerForm.confirmPassword" placeholder="确认密码">
                <template #prefix>
                  <span class="anticon anticon-lock" />
                </template>
              </a-input-password>
            </a-form-item>
            <a-form-item>
              <a-button 
                type="primary" 
                html-type="submit"
                :loading="registerLoading"
                class="login-btn"
                block
              >
                注册
              </a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'

const activeTab = ref('1')
const formState = reactive({
  username: '',
  password: ''
})
const autoLogin = ref(true)
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}
const formRef = ref()
const loading = ref(false)
const router = useRouter()

const loginRequest = async (payload) => {
  const res = await fetch('http://192.168.0.22:7044/api/module/Auth/Login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'accept': 'text/plain',
    },
    body: JSON.stringify(payload)
  })
  return res.json()
}

const handleSubmit = async () => {
  try {
    loading.value = true
    const response = await loginRequest({
      username: formState.username,
      password: formState.password
    })
    const { data, success, message: msg } = response
    if (success) {
      localStorage.setItem('accessToken', data.accessToken)
      localStorage.setItem('refreshToken', data.refreshToken)
      localStorage.setItem('user', JSON.stringify({ username: data.username, email: data.email }))
      message.success(msg || '登录成功')
      const redirect = router.currentRoute.value.query.redirect || '/psychology'
      await router.push(redirect)
      if (formRef.value) {
        try {
          await formRef.value.resetFields()
        } catch (e) {
          // eslint-disable-next-line no-empty
        }
      }
    } else {
      message.error(msg || '登录失败')
    }
  } catch (error) {
    message.error('登录请求失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 注册相关
const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})
const registerFormRef = ref()
const registerLoading = ref(false)
const registerRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value !== registerForm.password) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
}

const registerRequest = async (payload) => {
  const res = await fetch('http://192.168.0.22:7044/api/module/Auth/Register', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'accept': 'text/plain',
    },
    body: JSON.stringify(payload)
  })
  return res.json()
}

const handleRegister = async () => {
  try {
    registerLoading.value = true
    const response = await registerRequest({
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
      confirmPassword: registerForm.confirmPassword
    })
    const { success, message: msg } = response
    if (success) {
      message.success(msg || '注册成功，请登录')
      activeTab.value = '1'
      if (registerFormRef.value) {
        try {
          await registerFormRef.value.resetFields()
        } catch (e) {
          // eslint-disable-next-line no-empty
        }
      }
    } else {
      message.error(msg || '注册失败')
    }
  } catch (error) {
    message.error('注册请求失败: ' + (error.message || '未知错误'))
  } finally {
    registerLoading.value = false
  }
}
</script>

<script>
export default {
  name: 'LoginPage'
}
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(120deg, #f0f6ff 0%, #f7faff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-panel {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(31, 56, 88, 0.08);
  padding: 48px 48px 32px 48px;
  min-width: 400px;
  max-width: 420px;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.login-header {
  text-align: center;
  margin-bottom: 24px;
}
.login-logo {
  width: 56px;
  height: 56px;
  margin-bottom: 8px;
}
.login-title {
  font-size: 36px;
  font-weight: bold;
  color: #222;
  margin-bottom: 4px;
}
.login-subtitle {
  font-size: 16px;
  color: #888;
  margin-bottom: 12px;
}
.login-tabs {
  width: 100%;
}
.login-options {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}
.login-forgot {
  color: #1677ff;
  font-size: 14px;
  text-decoration: none;
}
.login-btn {
  font-size: 18px;
  height: 44px;
  border-radius: 6px;
  margin-top: 8px;
}
</style>
